/**
 * 微信小程序方法
 */

//  支付
function requestPayment(payParams) {
  return new Promise((resolve, reject) => {
    let {
      timeStamp,
      nonceStr,
      package: wxPackage,
      signType,
      paySign,
    } = payParams;
    wx.requestPayment({
      timeStamp,
      nonceStr,
      package: wxPackage,
      signType,
      paySign,
      success(res) {
        console.log("支付成功回调");
        console.log(res);
        resolve(true);
      },
      fail(res) {
        resolve(false);
      },
    });
  });
}

//  微信授权登录
function wxLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      async success(res) {
        const code = res.code;
        if (code) {
          resolve(code);
        } else {
          reject();
        }
      },
    });
  });
}

function showToast(title = "", icon = "none", duration = 2000) {
  wx.showToast({
    title,
    icon,
    duration,
  });
}

function showModal({
  title = "温馨提示",
  content = "",
  showCancel = false,
  confirmText = "我知道了",
  confirm,
  cancel,
}) {
  wx.showModal({
    title,
    content,
    showCancel,
    confirmText,
    success(res) {
      if (res.confirm) {
        confirm && confirm();
      } else if (res.cancel) {
        cancel && cancel();
      }
    },
  });
}

function showLoading(title = "", mask = false) {
  wx.showLoading({
    title,
    mask,
  });
}

function hideLoading() {
  wx.hideLoading({
    noConflict: true,
  });
}

function switchTab({ url }) {
  wx.switchTab({
    url,
  });
}

function reLaunch({ url }) {
  wx.reLaunch({
    url,
  });
}

function redirectTo({ url }) {
  wx.redirectTo({
    url,
  });
}

function navigateTo({ url, events }) {
  wx.navigateTo({
    url,
    events,
  });
}

function navigateBack() {
  wx.navigateBack();
}

function previewImage(current, urls) {
  wx.previewImage({
    current,
    urls,
  });
}

module.exports = {
  wxLogin,
  showToast,
  showModal,
  showLoading,
  hideLoading,
  switchTab,
  reLaunch,
  redirectTo,
  navigateTo,
  navigateBack,
  previewImage,
  requestPayment,
};
